﻿Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Text
Imports System.Xml

Public Class frmChangeConnect
    Dim connect As New connect()
    Dim con As SqlConnection
    Dim cmd As SqlCommand
    Dim dread As SqlDataReader
    Private Sub frmChangeConnect_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        server(".")
        server(".\sqlexpress")
    End Sub
    Sub server(ByVal str As String)
        con = New SqlConnection("Data Source=" & str & ";Database=Master;integrated security=SSPI;")
        con.Open()
        cmd = New SqlCommand("select *  from sysservers  where srvproduct='SQL Server'", con)
        dread = cmd.ExecuteReader
        While dread.Read
            cmbServer.Items.Add(dread(2))
        End While
        dread.Close()
    End Sub
    Sub connection()
        con = New SqlConnection("Data Source=" & Trim(cmbServer.Text) & ";Database=Master;integrated security=SSPI;")
        con.Open()
        cmbDatabase.Items.Clear()
        cmd = New SqlCommand("select * from sysdatabases", con)
        dread = cmd.ExecuteReader
        While dread.Read
            cmbDatabase.Items.Add(dread(0))
        End While
        dread.Close()
    End Sub
    Private Sub cmbserver_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbServer.SelectedIndexChanged
        connection()
    End Sub
    Private Sub change(ByVal str As String)
        Dim config As System.Configuration.Configuration = _
       ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
        config.ConnectionStrings.ConnectionStrings.Item("QLThueNha").ConnectionString = str
        config.Save()
    End Sub

    Private Sub btnSave_Click(sender As System.Object, e As System.EventArgs) Handles btnSave.Click
        Dim server As String = cmbServer.SelectedItem.ToString().Trim()
        Dim database As String = cmbDatabase.SelectedItem.ToString().Trim()
        Dim str As String = "Data Source=" + server + ";Initial Catalog=" + database + ";Integrated Security=True"
        change(str)
        MessageBox.Show("Đã Lưu thay đổi.")
    End Sub

    Private Sub btnExit_Click(sender As System.Object, e As System.EventArgs) Handles btnExit.Click
        Me.Close()
    End Sub
End Class